<template>
  <yq-dialog
    v-model="visible"
    width="70%"
    top="3vh"
    title="功能编辑"
    :allow-drag="false"
    :modal="false"
    :show-confirm-cancel-button="false"
    :before-close="() => {handleBefore()}"
    @open="handleOpen"
  >
    <div class="main">
      <el-container>
        <el-header>
          <span>我的功能
            <el-popover
              placement="bottom"
              title="说明"
              width="200"
              trigger="hover"
            >
              <div>
                1.我的功能项中白色按钮是用户编辑功能, 按钮右上角有'-'图标, 代表可以删除;<br>
                2.用户可以随意拖动我的功能tag项，最后点击右下角保存即可。
              </div>
              <el-button
                slot="reference"
                class="icon-button"
                style="border: none"
              ><img
                  style="height: 15px; width: 15px; transform:translate(-10px,-3px);"
                  src="../../../../assets/imges/question.png"
                  alt=""
                ></el-button>
            </el-popover>
          </span>
        </el-header>
        <el-main id="myTag">
          <el-col
            v-for="(munu, index) in myTags"
            :key="index"
            v-dragging="{ item: munu, list: myTags, group: 'name' }"
            style="width:20%"
          >
            <div
              class="my-card-panel"
              style="height: 100%"
            >
              <el-badge
                :style="`--color: ${ switchTag && munu.editValue ==='✓' ? 'red':'grey'}`"
                :value="switchTag ? munu.editValue : '-'"
                class="badge"
              >
                <el-button
                  class="pause-button"
                  :type="munu.addStatus.status"
                  @mouseover.native="mouseDown(munu)"
                  @mouseout.native="mouseOut(munu)"
                  @click="handleRemoveTag(munu, index)"
                >{{ $t(`route.${munu.meta.title}`) }}</el-button>
              </el-badge>
            </div>
          </el-col>
        </el-main>
      </el-container>
      <el-container>
        <el-header>所有功能</el-header>
        <el-main style="height:400px">
          <el-scrollbar style="height:100%">
            <el-row
              v-for="(munu, index1) in allTags"
              :key="index1"
            >
              <div style="font-size: 15px;font-weight: 800;margin-left: 20px; margin-top: 20px">{{ $t(`route.${munu.meta.title}`) }}</div>
              <div>
                <el-col
                  v-for="(tag, index2) in munu.tags"
                  :key="index2"
                  style="width:20%"
                >
                  <div class="all-card-panel">
                    <el-badge
                      :style="`--color: grey`"
                      :value="'+'"
                      class="badge"
                    >
                      <el-button
                        class="pause-button"
                        @click="handleAddTag(tag, index1, index2)"
                      >{{ $t(`route.${tag.meta.title}`) }}</el-button>
                    </el-badge>
                  </div>
                </el-col>
              </div>
            </el-row>
          </el-scrollbar>
        </el-main>
      </el-container>
    </div>
    <div class="foot">
      <span>
        <el-button
          type="primary"
          @click="handleConfirm"
        >保存</el-button>
      </span>
      <span>
        <el-button
          class="pause-button"
          @click="handleBefore"
        >取消</el-button>
      </span>
    </div>
  </yq-dialog>
</template>

<script>
import SystemConfigAPI from '@/api/system-config'

export default {
  name: 'SelectTag',
  components: {
  },
  directives: {
    drag: {
      // 指令的定义
      bind: function (el) {
        const dialog = document.getElementById('myTag')
        // Array.form() 浅拷贝转换数组
        // const allDragDiv = Array.from(document.getElementsByClassName('my-card-panel'))
        const odiv = el
        el.mouseover = (e) => {
          console.log('移入', e.client)
        }
        el.onmousedown = (e) => {
          // 算出鼠标相对元素的位置
          const disX = e.clientX - dialog.offsetLeft
          const disY = e.clientY - dialog.offsetTop
          let left = ''
          let top = ''
          document.onmousemove = (e) => {
            // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
            left = e.clientX - disX
            top = e.clientY - disY - 100
            // var docWidth = document.body.clientWidth// 网页可见宽
            // var docHeight = document.body.clientHeight//
            console.log(left, top)
            // 移动当前元素
            odiv.style.left = left + 'px'
            odiv.style.top = top + 'px'
          }
          document.onmouseup = () => {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      // 拖动
      dragList: [],
      switchTitle: '交换位置',
      switchTag: false,
      myTags: [],
      permissionData: this.$store.state.permission.addRoutes,
      allTags: [],
      defaultTags: [
        {
          redirect: '',
          addStatus: {
            index1: null,
            index2: null,
            status: 'success'
          },
          meta: {
            icon: 'customers',
            title: 'customers'
          },
          path: 'customers',
          name: 'Customers'
        },
        {
          redirect: '',
          addStatus: {
            index1: null,
            index2: null,
            status: 'success'
          },
          meta: {
            icon: 'paperData',
            title: 'paperData'
          },
          path: 'paperData',
          name: 'PaperData'
        },
        {
          redirect: '',
          addStatus: {
            index1: null,
            index2: null,
            status: 'success'
          },
          meta: {
            icon: 'cartonOrder',
            title: 'cartonOrder'
          },
          path: 'cartonOrder',
          name: 'CartonOrder'
        },
        {
          redirect: '',
          addStatus: {
            index1: null,
            index2: null,
            status: 'success'
          },
          meta: {
            icon: 'cartonDelivery',
            title: 'cartonDelivery'
          },
          path: 'cartonDelivery',
          name: 'CartonDelivery'
        },
        {
          redirect: '',
          addStatus: {
            status: 'success'
          },
          meta: {
            icon: 'cartonReturn',
            title: 'cartonReturn'
          },
          path: 'cartonReturn',
          name: 'CartonReturn'
        },
        {
          redirect: '',
          addStatus: {
            index1: null,
            index2: null,
            status: 'success'
          },
          meta: {
            icon: 'receivableStatement',
            title: 'receivableStatement'
          },
          path: 'receivableStatement',
          name: 'ReceivableStatement'
        }
      ]
    }
  },
  methods: {
    /* 遗留默认tag项为绿色、交换位置 */
    async handleOpen() {
      this.myTags = []
      await this.getCommonFunctions()
      this.switchTitle = '交换位置'
      this.switchTag = false
      this.allTags = this.getAllTags()
      await this.repartTags()
    },
    insertCommonFunctions() {
      const tags = JSON.parse(JSON.stringify(this.myTags))
      tags.map(item => {
        item.index1 = item.addStatus.index1
        item.index2 = item.addStatus.index2
        item.status = item.addStatus.status
        item.icon = item.meta.icon
        item.title = item.meta.title
        delete item.addStatus
        delete item.meta
      })
      const params = {
        type: '01',
        moduleIdList: tags
      }
      SystemConfigAPI.addOne('insertCommonFunction', params).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.$emit('update-tag', this.myTags)
          this.setVisible(false)
        }
      })
    },
    async getCommonFunctions() {
      await SystemConfigAPI.getList('commonFunction').then(res => {
        if (res.code === 200) {
          const list = res.data.pageItems
          if (list.length > 0) {
            list.map(item => {
              item.addStatus = {
                index1: item.index1,
                index2: item.index2,
                status: item.status
              }
              item.meta = {
                icon: item.icon,
                title: item.title
              }
              delete item.index1
              delete item.index2
              delete item.status
              delete item.icon
              delete item.title
            })
            this.myTags = list
          }
        }
      })
    },
    handleConfirm() {
      this.insertCommonFunctions()
    },
    handleBefore() {
      this.setVisible(false)
    },
    setVisible(flag) {
      this.$emit('update:visible', flag)
    },
    handleSwitchTag() {
      this.switchTag = !this.switchTag
      if (this.switchTag) {
        this.switchTitle = '结束交换'
        this.myTags.map(tag => {
          tag.editValue = '?'
        })
      } else {
        this.switchTitle = '交换位置'
        this.myTags.map(tag => {
          delete tag.editValue
        })
      }
    },
    handleAddTag(tag, index1, index2) {
      const isRepeat = this.myTags.some(item => item.name === tag.name)
      if (isRepeat) return this.$message.warning('该功能已添加到常用功能！')
      if (this.myTags.length > 9) return this.$message.warning('常用功能不能超过十条！')
      this.allTags[index1].tags.splice(index2, 1)
      const addTag = Object.assign({}, tag)
      addTag.addStatus = {
        status: 'add',
        index1: index1,
        index2: index2
      }
      this.myTags.push(addTag)
    },
    handleRemoveTag(tag, index) {
      if (this.switchTag) {
        if (tag.addStatus.status === 'success') {
          return this.$message.warning('固定功能不可移动')
        }
        tag.editValue = '✓'
        const filterList = this.myTags.filter(item => item.editValue === '✓')
        if (filterList.length > 1) {
          const index1 = this.myTags.findIndex(item => item === filterList[0])
          const tag1 = this.myTags.find(item => item === filterList[0])
          const index2 = this.myTags.findIndex(item => item === filterList[1])
          const tag2 = this.myTags.find(item => item === filterList[1])
          this.myTags.splice(index1, 1)
          this.myTags.splice(index1, 0, tag2)
          this.myTags.splice(index2, 1)
          this.myTags.splice(index2, 0, tag1)
          this.myTags.map(tag => {
            tag.editValue = '?'
          })
        }
      } else {
        if (tag.addStatus.status === 'success') {
          this.myTags.splice(index, 1)
        } else {
          this.myTags.splice(index, 1)
          const removeTag = Object.assign({}, tag)
          delete removeTag.addStatus
          this.allTags[tag.addStatus.index1].tags.splice(tag.addStatus.index2, 0, removeTag)
        }
      }
      this.$forceUpdate()
    },
    mouseDown(tag) {
      if (tag.addStatus.status !== 'success') tag.addStatus.status = 'danger'
    },
    mouseOut(tag) {
      if (tag.addStatus.status !== 'success') tag.addStatus.status = null
    },
    getAllTags() {
      const list = []; const tag = []
      const permissionData = [...this.permissionData]
      permissionData.forEach((item, index) => {
        list[index] = item
        list[index].tags = []
        if (item.children) {
          item.children.forEach(child => {
            if (child.children) {
              child.children.forEach(sun => {
                if (sun.children) {
                  sun.children.forEach(son => list[index].tags.push(son))
                } else {
                  list[index].tags.push(sun)
                }
              })
            } else {
              list[index].tags.push(child)
            }
          })
        }
      })
      const data = list.filter(e => { return e.tags.length !== 0 })
      data.map(item => {
        if (this.hasChinese(this.$t(`route.${item.meta.title}`))) {
          tag.push(item)
        }
      })
      return tag
    },
    repartTags() {
      if (this.myTags.length === 0) {
        this.myTags = []
        const allTag = JSON.parse(JSON.stringify(this.allTags))
        allTag.forEach((munu, index1) => {
          munu.tags.map((tag, index2) => {
            if (this.defaultTags.some(item => this.$t(`route.${tag.meta.title}`) === this.$t(`route.${item.meta.title}`))) {
              // mytag 增加
              this.allTags[index1].tags.splice(index2, 1)
              const addTag = Object.assign({}, tag)
              addTag.addStatus = {
                status: 'add',
                index1: index1,
                index2: index2
              }
              this.myTags.push(addTag)
            }
          })
        })
      } else {
        this.myTags.map(tag => {
          if (tag.addStatus.status === 'add') {
            // this.allTags[tag.addStatus.index1].tags.splice(tag.addStatus.index2, 1)
          }
        })
      }
    },
    hasChinese(str) {
      return /[\u4E00-\u9FA5]+/g.test(str)
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  height: 100%;
  width: 100%;
  .el-header {
    color: black;
    font-weight: 800;
    font-size: 18px;
    text-align: start;
    line-height: 30px;
    height: 30px !important;
  }
  .my-card-panel {
    height: 100%;
    width: 100%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    color: #666;
    text-align: center;
    margin: 5px 0;
    .badge {
      margin-top: 10px;
    }
    button {
      width: 150px;
      height: 45px;
      font-size: 15px;
    }
  }
  .all-card-panel {
    height: 100%;
    width: 100%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    color: #666;
    text-align: center;
    margin: 5px 0;
    .badge {
      margin-top: 10px;
    }
    button {
      width: 150px;
      height: 45px;
      font-size: 15px;
    }
  }
}
.foot {
  text-align: right;
  background: transparent;
  border-radius: 0 0 4px 4px;
  padding-top: 10px;
  button {
    height: 30px;
    width: 85px;
    margin-left: 15px;
  }
}
/deep/ .el-select-dropdown .el-scrollbar {
  padding-bottom: 17px;
}
/deep/ .el-scrollbar__wrap {
  overflow-x: hidden !important;
}
/deep/ .el-badge__content {
  background-color: var(--color);
  opacity: 0.5;
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  /* text-align: center; */
  white-space: nowrap;
  border: 1px solid #fff;
}
</style>
